package com.chouxiaozi.wechatpublic.controller;

import com.chouxiaozi.wechatpublic.commons.CoreConsts;
import com.chouxiaozi.wechatpublic.commons.JsonResult;
import com.chouxiaozi.wechatpublic.entity.WechatGroup;
import com.chouxiaozi.wechatpublic.service.IWechatGroupService;
import com.chouxiaozi.wechatpublic.service.InitializeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.weixin4j.WeixinException;

@Controller
@RequestMapping("/initialize")
public class InitializeController extends BaseController {

	@Autowired
	private InitializeService initializeService;

	@Autowired
	private IWechatGroupService wechatGroupService;



	/**
	 *  platfprm 点击生效 进行初始化当前公众号        菜单 关键词回复  关注回复
	 * @return
	 * @throws WeixinException
	 */
	@RequestMapping(value="/iniWechat")
	@ResponseBody
	public JsonResult receivePacket(ModelMap modelMap, Integer groupId) {

		if(groupId==null) {
			return this.wrapFailResult(CoreConsts.RESULT_CODE_ERROR, "微信群组id不能为空");
		}

		try {
			initializeService.initalizeWechat(groupId);

			return this.wrapSuccessResult(null);
		} catch (Exception e) {
			logger.error("初始化公众号异常:{}", e);
			return this.wrapFailResult(CoreConsts.RESULT_CODE_ERROR, "初始化失败:"+e.getMessage());
		}
	}

	/**
	 *  自定义菜单后生效微信菜单
	 * @return
	 * @throws WeixinException
	 */
	@RequestMapping(value="/effectWechatMenu")
	@ResponseBody
	public JsonResult effectWechatMenu(ModelMap modelMap, Integer groupId)  {


		try {
			if(groupId==null) {
				return this.wrapFailResult(CoreConsts.RESULT_CODE_ERROR, "微信群组id不能为空");
			}

			WechatGroup group =  wechatGroupService.getById(groupId);
			if(group==null) {
				return this.wrapFailResult(CoreConsts.RESULT_CODE_ERROR, "未找到对应微信群组");
			}
			initializeService.effectWxMenu(group);
			return this.wrapSuccessResult(null);
		} catch (Exception e) {
			logger.error("生效微信菜单异常:{}", e);
			return this.wrapFailResult(CoreConsts.RESULT_CODE_ERROR, "生效微信菜单:"+e.getMessage());
		}
	}

}
